package com.wanchuang.shengfubao.web.ui;


import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.wanchuang.shengfubao.R;
import com.wanchuang.shengfubao.base.BaseFragment;
import com.wanchuang.shengfubao.help.PermissionHelper;
import com.wanchuang.shengfubao.help.UserHelper;
import com.wanchuang.shengfubao.utils.GsonUtils;
import com.wanchuang.shengfubao.utils.ImageUtil;
import com.wanchuang.shengfubao.utils.LogUtil;
import com.wanchuang.shengfubao.utils.SaveViewToImageUtil;
import com.wanchuang.shengfubao.utils.ValidateUtils;
import com.wanchuang.shengfubao.web.inteface.JavaScriptInterface;
import com.wanchuang.shengfubao.web.manager.MyChromeClient;
import com.wanchuang.shengfubao.web.manager.WebViewClientUtil;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.wanchuang.shengfubao.web.ui.WebViewActivity.DOWNLOAD;
import static com.wanchuang.shengfubao.web.ui.WebViewActivity.GOTOCAPTURE;
import static com.wanchuang.shengfubao.web.ui.WebViewActivity.JUMPTO;
import static com.wanchuang.shengfubao.web.ui.WebViewActivity.SAVE;


/**
 * Created by Frank on 2018/1/9.
 */

public class WebViewFragment extends BaseFragment implements WebViewClientUtil.WebClientLoadListener,
        MyChromeClient.ProgressChangedListener, MyChromeClient.ReceivedTitleListener {

    Unbinder unbinder;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.prograssBar)
    ProgressBar prograssBar;
    @BindView(R.id.rv_message)
    RelativeLayout rvMessage;

    private Handler jsInterfaceHandler;
    private String url;

    public static  WebViewFragment newInstance(String url) {
      WebViewFragment fragment = new WebViewFragment();
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_web_view;
    }

    @Override
    protected void initView() {
        url = getArguments().getString("url");
        jsInterfaceHandler = new JsInterfaceHandler(this.getActivity(), webView, rvMessage);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new JavaScriptInterface(jsInterfaceHandler), "app");
        webView.setWebViewClient(new WebViewClientUtil(getActivity(), this));
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setLoadsImagesAutomatically(true);// 加载网页中的图片
        webView.getSettings().setUseWideViewPort(true); //设置使用视图的宽端口
        webView.setWebChromeClient(new MyChromeClient(getActivity(), this, this, webView, null));
        webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        if (UserHelper.isLogin()) {
            syncCookie(getActivityContext(), url);   //同步cookie
        }
        loadUrl();
    }

    @Override
    protected void init() {

    }

    private void loadUrl() {
        String newUrl;
        //统一拼接可
        if (UserHelper.isLogin()) {
            if (url.contains("?")) {
                newUrl = url + "&key=" + UserHelper.getCurrentToken();
            } else {
                newUrl = url + "?key=" + UserHelper.getCurrentToken();
            }
        } else {
            newUrl = url;
        }
        webView.loadUrl(newUrl);
        LogUtil.e("frank", "WebViewFragment网页请求地址：" + newUrl);
    }


    //同步cookie
    private void syncCookie(Context context, String url) {
        try {
            CookieSyncManager.createInstance(context);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeAllCookie();
            cookieManager.setCookie(url, "key=" + UserHelper.getCurrentToken());
            String newCookie = cookieManager.getCookie(url);
            if (newCookie != null) {
                LogUtil.d("frank", "设置Cookie url=" + url + " ;   cookie=" + newCookie);
            }
        } catch (Exception e) {
            LogUtil.e("Frank: webView.syncCookie failed", e.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void loadFinished(String title, boolean isError) {

    }



    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        Log.e("onProgressChanged", newProgress + "\n");
        //进度显示
        if (newProgress > 80) {
            prograssBar.setVisibility(View.GONE);
        } else {
            prograssBar.setProgress(newProgress);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {

    }


    /*--------------------------------H5 调用原生--------------------------------*/

    private static class JsInterfaceHandler extends Handler {
        private Activity context;
        private WebView webViews;
        private RelativeLayout contentLayout;
        private RelativeLayout totalBgLayout;

        public JsInterfaceHandler(Activity activity, WebView webViews, RelativeLayout contentLayout) {
            this.context = activity;
            this.webViews = webViews;
            this.contentLayout = contentLayout;
        }


        @Override
        public void handleMessage(Message msg) {
            if (ValidateUtils.isValidate(msg.obj)) {
                switch (msg.what) {
                    case JUMPTO:
                        WebViewActivity.startActivity(context, msg.obj.toString(), false);
                        break;
                    case GOTOCAPTURE:
                        captureWebView1(context, webViews);
                        break;
                    case DOWNLOAD:
                        String dl_s = (String) msg.obj;
                        String[] dl_strings = dl_s.split(",");
//                        downloadImage(context, dl_strings[0], webViews, dl_strings[1]);
                        break;
                    case SAVE:
                        String sa_s = (String) msg.obj;
//                        String[] sa_strings = sa_s.split(",");
//                        saveImage(context, sa_strings[0], sa_strings[1], webViews);
                        QrMessageBean qrMessageBean = GsonUtils.jsonToBean(sa_s, QrMessageBean.class);
                        Log.e("message", qrMessageBean.toString());
                        captureWebView2(context, webViews, contentLayout, qrMessageBean);
                        break;
                }

            }

        }
    }


    /**
     * 对WebView进行截图
     *
     * @param webView
     * @return
     */
    public static void captureWebView1(Context context, View webView) {//可执行
        PermissionHelper.getInstance().getPermission((FragmentActivity)context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(webView);
                String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "截图";
                String fileName = System.currentTimeMillis() + ".jpg";
                boolean b = ImageUtil.saveImageToGallery(context, viewBitmap, storePath, fileName);
                if (b) {
                    Toast.makeText(context, "截图保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 3.0通用下载图片
     *
     * @param contentView
     * @return
     */
    public static void captureWebView2(Context context, WebView webView, RelativeLayout contentView, QrMessageBean messageBean) {
        PermissionHelper.getInstance().getPermission((FragmentActivity)context, new PermissionHelper.PermissionCallBack() {
            @Override
            public void onSuccess() {
                Glide.with(context)
                        .asBitmap()
                        .load(messageBean.getAdvCode())
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                if (messageBean.getIsAdditional().equals("1")) {  // 需要加载信息数据
                                    contentView.setVisibility(View.VISIBLE);
                                    TextView memberName = contentView.findViewById(R.id.tv_message_title);
                                    memberName.setText(messageBean.getMemberName());
                                    TextView textss = contentView.findViewById(R.id.tv_message_text);
                                    textss.setText(messageBean.getText());
                                    TextView tip = contentView.findViewById(R.id.tv_message_tips);
                                    tip.setText(messageBean.getTip());
                                    ImageView qrView = contentView.findViewById(R.id.iv_message_qr);
                                    Glide.with(context)
                                            .load(messageBean.getQrcodeUrl())
                                            .into(new CustomTarget<Drawable>() {
                                                @Override
                                                public void onResourceReady(@NonNull Drawable drawableResource, @Nullable Transition<? super Drawable> transition) {
                                                    qrView.setImageDrawable(drawableResource);
                                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                                    String fileName = System.currentTimeMillis() + ".png";
                                                    Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(contentView);
                                                    float widthScale = (float) resource.getWidth() / (float) viewBitmap.getWidth();
                                                    Matrix matrix = new Matrix();
                                                    matrix.postScale(widthScale, widthScale);  //长和宽放大缩小的比例
                                                    Bitmap resizeBmp = Bitmap.createBitmap(viewBitmap, 0, 0, viewBitmap.getWidth(),
                                                            viewBitmap.getHeight(), matrix, true);
                                                    Bitmap ImageBitmap = Bitmap.createBitmap(resource.getWidth(), resource.getHeight()+resizeBmp.getHeight(),
                                                            resource.getConfig());
                                                    Canvas canvas = new Canvas(ImageBitmap);
                                                    canvas.drawBitmap(resource, new Matrix(), null);
                                                    canvas.drawBitmap(resizeBmp, 0, resource.getHeight(), null);
                                                    boolean b = ImageUtil.saveImageToGallery(context, ImageBitmap, storePath, fileName);
                                                    if (b) {
                                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                                        //获取剪贴板管理器
                                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                                        // 创建普通字符型ClipData
                                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                                        // 将ClipData内容放到系统剪贴板里。
                                                        cm.setPrimaryClip(mClipData);
                                                    } else {
                                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                    }
                                                }

                                                @Override
                                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                                    Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                                    webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                                }
                                            });
                                } else {
                                    String storePath = context.getFilesDir().getAbsolutePath() + File.separator + "截图";
                                    String fileName = System.currentTimeMillis() + ".png";
                                    boolean b = ImageUtil.saveImageToGallery(context, resource, storePath, fileName);
                                    if (b) {
                                        Toast.makeText(context, "保存成功，请在相册查看", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getSuccess() + "()");
                                        //获取剪贴板管理器
                                        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
                                        // 创建普通字符型ClipData
                                        ClipData mClipData = ClipData.newPlainText("Label", messageBean.getCopyText());
                                        // 将ClipData内容放到系统剪贴板里。
                                        cm.setPrimaryClip(mClipData);
                                    } else {
                                        Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                        webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                                    }
                                }


                            }

                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                                Toast.makeText(context, "保存失败，请重试", Toast.LENGTH_SHORT).show();
                                webView.loadUrl("javascript:" + messageBean.getFail() + "()");
                            }
                        });
            }

            @Override
            public void onFail() {
                Toast.makeText(context, "获取权限失败", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


    }
}
